<template>
  <div>
    <el-row>
      <el-col :span="22">
        <el-alert
          :title="infoAlert.title"
          :type="infoAlert.type"
          center
          show-icon
          :closable="false"
          style="margin-bottom: 15px"
        ></el-alert>
      </el-col>
      <el-col :span="2">
        <el-button
          type="primary"
          v-print="'#formTable'"
          style="float: right"
          @click="handlePrint"
          >打印</el-button
        >
      </el-col>
    </el-row>
    <el-row>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <treeselect
                v-model="form.deptId"
                :options="deptOptions"
                :show-count="true"
                placeholder="请选择归属部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目编号" prop="projectOn">
              <el-input
                v-model="form.projectOn"
                placeholder="请输入项目编号"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商机名称" prop="projectName">
              <el-input
                v-model="form.projectName"
                placeholder="请输入商机名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerId">
              <el-select
                v-model="form.customerId"
                placeholder="请选择客户名称"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="customer in customerList"
                  :key="customer.customerId"
                  :label="customer.customerName"
                  :value="customer.customerId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startTime">
              <el-date-picker
                clearable
                style="width: 100%"
                v-model="form.startTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择开始日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endTime">
              <el-date-picker
                clearable
                style="width: 100%"
                v-model="form.endTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="申请人" prop="applyUser">
              <el-select
                v-model="form.applyUser"
                placeholder="请选择申请人"
                style="width: 100%"
                filterable
                clearable
              >
                <el-option
                  v-for="user in userList"
                  :key="user.userId"
                  :label="user.userName"
                  :value="user.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="principalId">
              <el-select
                v-model="form.principalId"
                placeholder="请选择负责人"
                style="width: 100%"
                filterable
                clearable
                multiple
              >
                <el-option
                  v-for="user in userList"
                  :key="user.userId"
                  :label="user.userName"
                  :value="user.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="回款情况" prop="payment">
              <el-input
                v-model="form.payment"
                placeholder="请输入回款情况说明"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="项目金额" prop="projectSum">
              <el-input v-model="form.projectSum" placeholder="请输入项目金额">
                <template slot="append">{{
                  digitUppercase(form.projectSum)
                }}</template></el-input
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="最终利润" prop="profit">
              <el-input
                v-model="form.profit"
                placeholder="请输入最终利润"
                readonly
              >
                <template slot="append">{{
                  digitUppercase(form.profit)
                }}</template></el-input
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="利润率" prop="profitMargin">
              <el-input
                v-model="form.profitMargin"
                placeholder="请输入利润率"
                readonly
              >
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-divider>项目成本费用支出</el-divider>
            <div class="box">
              <el-card
                class="box-card"
                shadow="never"
                v-for="(details, index) in form.detailsList"
                :key="index"
              >
                <el-row>
                  <el-col :span="20">
                    <el-form-item label="是否存在明细" prop="isRequired">
                      <el-checkbox
                        v-model="details.isRequired"
                        true-label="1"
                        false-label="0"
                        :disabled="
                          details.detailsAmount !== null &&
                          details.detailsAmount !== ''
                        "
                        >无</el-checkbox
                      >
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item prop="isRequired">
                      <div style="float: right">
                        <el-button type="text" @click="addExpenses(details, index)">新增</el-button>
                        <el-button type="text" style="color: red" @click="delExpenses(index)"
                          >删除</el-button
                        >
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="details.itemWidth">
                    <el-form-item label="费用类型" prop="detailsName">
                      <el-select
                        v-model="details.detailsType"
                        placeholder="请选择费用类型"
                        style="width: 100%"
                        :disabled="details.isRequired === '1' || details.flag === '1'"
                        @change="detailsTypeChange(details)"
                      >
                        <el-option
                          v-for="dict in dict.type.crm_fee_type"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="details.itemWidth">
                    <el-form-item label="费用名称" prop="detailsName">
                      <el-input
                        :readonly="details.flag === '1'"
                        v-model="details.detailsName"
                        placeholder="请输入费用名称"
                        :disabled="details.isRequired === '1'"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col
                    :span="8"
                    v-if="details.detailsType === '1' || details.detailsType === '4'"
                  >
                    <el-form-item label="费用来源" prop="url">
                      <el-select
                        v-model="details.applyIds"
                        multiple 
                        filterable 
                        placeholder="请选择费用来源"
                        style="width: 100%"
                        :disabled="details.isRequired === '1' || details.flag === '1'"
                        @change="setterApplyAmount($event, details)"
                      >
                        <el-option
                          v-for="apply in applyList"
                          :key="apply.applyId"
                          :label="apply.applyName"
                          :value="apply.applyId"
                        >
                          <span style="float: left">{{ apply.applyName }}</span>
                          <span style="float: right; color: #8492a6; font-size: 13px">￥ {{ apply.amount }} 元</span>
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="预算合计" prop="detailsAmount">
                      <el-input
                        v-model="details.detailsAmount"
                        placeholder="请输入预算合计"
                        type="number"
                        :disabled="details.isRequired === '1'"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="费用描述" prop="detailsDesc">
                      <el-input
                        v-model="details.detailsDesc"
                        placeholder="请输入费用详情描述"
                        :disabled="details.isRequired === '1'"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="备注" prop="remark">
                      <el-input
                        v-model="details.remark"
                        placeholder="请输入备注"
                        :disabled="details.isRequired === '1'"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-card>
              <!-- 其他明细新增按钮 -->
            </div>

            <el-divider>
              <el-button
                type="text"
                icon="el-icon-plus"
                @click="addExpenses(null)"
              >
                其他明细新增
              </el-button></el-divider
            >
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="费用总计" prop="aggregationCharge">
              <el-input
                readonly
                v-model="form.aggregationCharge"
                placeholder="请输入费用总计"
              >
                <template slot="append">{{
                  digitUppercase(form.aggregationCharge)
                }}</template></el-input
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="管理层意见" prop="opinion">
              <el-input v-model="form.opinion" placeholder="请输入管理层意见" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件" prop="url">
              <file-upload v-model="form.url" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" v-if="!disabled">
            <el-form-item>
              <el-button type="primary" @click="submitForm('1')"
                >提 交</el-button
              >
              <el-button type="info" @click="submitForm('0')">暂 存</el-button>
              <el-button @click="cancel">取 消</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-row>
    <projectClear
      id="formTable"
      :tabledata="form"
      :ownerList="userList"
      :customerList="customerList"
      :deptOptions="deptOptions"
      v-show="showProjectApproval"
    />
  </div>
</template>

<script>
import {
  selectCrmFeeApplyByOrderIdAndCreateBy
} from "@/api/crm/apply";

import {
  addClear,
  updateClear,
  orderClearInit,
  getInfoByOrderId
} from "@/api/crm/clear";

import { deptTreeSelect } from "@/api/system/user";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import projectClear from "../components/projectClear.vue";
export default {
  name: "OrderRegister",
  dicts: ["crm_order_nature", "crm_order_contracts", "crm_fee_type"],
  props: {
    userList: {
      type: Array,
      default: [],
    },
    customerList: {
      type: Array,
      default: [],
    },
    orderInfo: {
      type: Object,
      default: () => {},
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    Treeselect,
    projectClear,
  },
  data() {
    return {
      infoAlert: {
        type: "info",
        title: "待填写",
      },
      // 商机项目立项表格数据
      orderRegisterList: [],
      // 弹出层标题
      title: "",
      // 表单参数
      form: {
        detailsList: []
      },
      // 表单校验
      rules: {
        orderId: [
          { required: true, message: "商机id不能为空", trigger: "blur" },
        ],
        deptId: [
          { required: true, message: "所属部门id不能为空", trigger: "blur" },
        ],
        projectOn: [
          { required: true, message: "项目编号不能为空", trigger: "blur" },
        ],
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" },
        ],
        projectTime: [
          { required: true, message: "立项时间不能为空", trigger: "blur" },
        ],
        customerId: [
          { required: true, message: "客户id不能为空", trigger: "blur" },
        ],
        applyUser: [
          { required: true, message: "申请人id不能为空", trigger: "blur" },
        ],
        principalId: [
          { required: true, message: "负责人不能为空", trigger: "blur" },
        ],
        nature: [
          { required: true, message: "项目性质不能为空", trigger: "change" },
        ],
        startTime: [
          { required: true, message: "开始日期不能为空", trigger: "blur" },
        ],
        endTime: [
          { required: true, message: "结束日期不能为空", trigger: "blur" },
        ],
        projectSum: [
          { required: true, message: "项目金额不能为空", trigger: "blur" },
        ],
        profit: [
          { required: true, message: "预计利润不能为空", trigger: "blur" },
        ],
        profitMargin: [
          { required: true, message: "利润率不能为空", trigger: "blur" },
        ],
        aggregationCharge: [
          { required: true, message: "费用总计不能为空", trigger: "blur" },
        ],
        laborContracts: [
          { required: true, message: "签订单位不能为空", trigger: "change" },
        ],
        paymentTime: [
          { required: true, message: "付款方式不能为空", trigger: "change" },
        ],
      },
      deptOptions: [],
      showProjectApproval: false,
      itemWidth: 12, // 动态列宽
      applyList: []
    };
  },
  created() {
    this.selectCrmFeeApplyByOrderIdAndCreateBy()
  },
  watch: {
    "form.projectSum"() {
      // 计算公司明细
      let obj = this.form?.detailsList?.find(
        (item) => "公司明细" === item.detailsName
      );
      obj.detailsAmount = (this.form.projectSum * 0.03).toFixed(2);
    },
    "form.detailsList": {
      handler(val) {
        
        if(!val) return
        // 计算支出总金额
        const totalAmount = this.form.detailsList.reduce((sum, item) => {
          const amount = parseFloat(item.detailsAmount) || 0;
          return sum + amount;
        }, 0);

        // 计算利润
        const profit = (this.form.projectSum - totalAmount).toFixed(2);
        this.$set(this.form, "profit", profit);

        // 计算利润率
        const profitMargin =
          this.form.projectSum > 0
            ? ((profit / this.form.projectSum) * 100).toFixed(2)
            : "0";
        this.$set(this.form, "profitMargin", profitMargin);

        this.form.aggregationCharge = totalAmount;
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    setterApplyAmount(rows, details){
      details.detailsAmount = 0
      rows.forEach(row => {
        const apply = this.applyList.find(item => item.applyId === row)
        details.detailsAmount += apply.amount
      })
    
    },
    // 费用类型变化事件
    detailsTypeChange(details) {
      details.itemWidth = details.detailsType === "1" || details.detailsType === "4" ? 8 : 12;
    },
    selectCrmFeeApplyByOrderIdAndCreateBy(){
      selectCrmFeeApplyByOrderIdAndCreateBy(this.orderInfo.orderId).then(res => {
        this.applyList = res.data
      })
    },
    // 添加明细
    addExpenses(details, index) {
      if (details) {
        this.form.detailsList.splice(index + 1, 0, {
          detailsName: details.detailsName,
          detailsType: details.detailsType,
          detailsDesc: null,
          detailsAmount: null,
          remark: null,
          isRequired: "0",
          flag: "0",
          itemWidth: details.detailsType === "1" || details.detailsType === "4" ? 8 : 12
        });
      } else {
        this.form.detailsList.push({
          detailsName: null,
          detailsType: '7',
          detailsDesc: null,
          detailsAmount: null,
          remark: null,
          isRequired: "0",
          flag: "0",
          itemWidth: 12
        });
      }
    },
    delExpenses(index) {
      this.form.detailsList.splice(index, 1);
    },
    handlePrint() {
      this.showProjectApproval = true;
      setTimeout(() => {
        this.showProjectApproval = false;
      }, 2000);
    },
    getData() {
      this.getDeptTree();
    },
    async getOrderCleartInfo() {
      getInfoByOrderId(this.orderInfo.orderId).then(res => {
        this.form = res.data
        if (this.form) {
          // 根据审核状态设置提示
          switch (this.form.auditStatus) {
            case "0":
              this.infoAlert = { type: "info", title: "待提交" };
              break;
            case "1":
              this.infoAlert = { type: "warning", title: "待审核" };
              break;
            case "2":
              this.infoAlert = { type: "success", title: "审核通过" };
              break;
            case "3":
              this.infoAlert = { type: "error", title: "审核不通过" };
              break;
            case "4":
              this.infoAlert = { type: "warning", title: "审核中" };
              break;
          }

          this.form.principalId = this.form.principalId
            ? this.form.principalId.split(",")
            : null;
          this.form.detailsList.forEach(element => {
            this.detailsTypeChange(element)
            this.$forceUpdate()
          });
        } else {
          orderClearInit(this.orderInfo.orderId).then((res) => {
            this.form = res.data;
            this.form.principalId = this.form.principalId
              ? this.form.principalId.split(",")
              : null;
            this.form.projectName = this.orderInfo.orderName;

            this.form.detailsList.forEach(element => {
              this.detailsTypeChange(element)
              this.$forceUpdate()
            });
          });
        }
      })
    },
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
        this.getOrderCleartInfo();
      });
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    cancel() {
      this.reset();
      this.$emit("cancel");
    },
    /** 提交按钮 */
    submitForm(auditStatus) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.orderId = this.orderInfo.orderId;
          this.form.auditStatus = auditStatus;
          let obj = {...this.form}
          obj.principalId = this.form.principalId
            ? this.form.principalId.join(",")
            : null;
          if (this.form.id != null) {
            updateClear(obj).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.getOrderCleartInfo();
            });
          } else {
            addClear(obj).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.getOrderCleartInfo();
            });
          }
        }
      });
    },
  },
};
</script>

<style scoped>
::v-deep .details .el-table--medium .el-table__cell {
  padding: 0;
  border-bottom: none;
}

::v-deep .details .el-input--medium {
  margin: 10px 10px 10px -10px;
}

.box-card {
  margin: 20px;

}
.box {
  overflow: auto;
  max-height: 600px;
  background-color: #f5f7fa;
}
</style>